// ignore_for_file: library_private_types_in_public_api
import 'dart:collection';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:photo_manager/photo_manager.dart';
import 'package:wallpaper/components/AlertDialog/my_loading.dart';
import 'package:wallpaper/components/placeholder/appbar_base.dart';
import 'package:wallpaper/components/placeholder/empty.dart';
import 'package:wallpaper/model/options_base.dart';
import 'package:wallpaper/pages/other/local/local_image_view%20copy.dart';
import 'package:wallpaper/tools/route_animation.dart';

import '../../../components/images/BlinkingPlaceholder.dart';

class AlbumImageListPage extends StatefulWidget {
  // 接收上层传递的相册对象
  final AssetPathEntity album;

  const AlbumImageListPage({super.key, required this.album});

  @override
  _AlbumImageListPageState createState() => _AlbumImageListPageState();
}

class _AlbumImageListPageState extends State<AlbumImageListPage> {
  /* ---------------- 核心参数 ---------------- */
  static const int _pageSize = 60; // 一次加载图片数量
  static const int _cacheCapacity = 200; // 缩略图内存缓存上限

  final LinkedHashMap<String, Uint8List> _thumbCache =
      LinkedHashMap<String, Uint8List>(); // 缩略图LRU缓存
  final List<AssetEntity> _assets = []; // 已加载的图片Asset
  final List<String> _imagePaths = []; // 原图路径缓存（用于查看页）

  int _page = 0; // 当前加载页数
  bool _hasMore = true; // 是否还有更多数据
  bool _isLoading = false; // 是否正在加载

  @override
  void initState() {
    super.initState();
    // 初始化加载第一页
    _loadPage();
  }

  @override
  void dispose() {
    super.dispose();
  }

  Future<void> _loadPage() async {
    if (!_hasMore) return;
    setState(() => _isLoading = true);

    try {
      final start = _page * _pageSize;
      final end = start + _pageSize;
      final newAssets =
          await widget.album.getAssetListRange(start: start, end: end);
      if (newAssets.isEmpty) {
        setState(() => _hasMore = false);
        return;
      }

      // 处理新加载的Asset：缓存原图路径
      for (final asset in newAssets) {
        final file = await asset.file;
        if (file != null) {
          _imagePaths.add(file.path); // 缓存原图路径，用于跳转查看页
        }
      }

      // 更新状态：添加新Asset、页数+1
      setState(() {
        _assets.addAll(newAssets);
        _page++;
      });
    } catch (e) {
      debugPrint('加载图片列表失败: $e');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text("图片加载失败")),
        );
      }
    } finally {
      if (mounted) setState(() => _isLoading = false);
    }
  }

  /* ---------------- 缩略图获取与缓存 ---------------- */
  Future<Uint8List?> _getThumbnail(AssetEntity asset) async {
    // 1. 优先从LRU缓存获取
    if (_thumbCache.containsKey(asset.id)) return _thumbCache[asset.id]!;
    // 2. 缓存未命中，生成250x250缩略图
    final thumbBytes =
        await asset.thumbnailDataWithSize(const ThumbnailSize(250, 250));
    // 3. 存入缓存并执行LRU淘汰
    if (thumbBytes != null) {
      _thumbCache[asset.id] = thumbBytes;
      _evictLRUCache();
    }
    return thumbBytes;
  }

  /* ---------------- LRU缓存淘汰策略 ---------------- */
  void _evictLRUCache() {
    while (_thumbCache.length > _cacheCapacity) {
      _thumbCache.remove(_thumbCache.keys.first); // 移除最早加入的缓存项
    }
  }

  /* ---------------- 跳转图片查看页 ---------------- */
  void _navigateToImageView(int index) {
    RouteAnimation().animateRoute(
        context,
        LocalImageView(
          images: _imagePaths, // 传入缓存的原图路径
          selectedIndex: index,
        ));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppbarBase(title: widget.album.name),
      body: NotificationListener<ScrollNotification>(
        // 使用NotificationListener监听滚动事件
        onNotification: (ScrollNotification scrollInfo) {
          double bottomDistance =
              scrollInfo.metrics.maxScrollExtent - scrollInfo.metrics.pixels;
          // 检测是否滚动到底部附近
          if (scrollInfo is ScrollUpdateNotification && bottomDistance <= 200) {
            if (!_hasMore || _isLoading) {
              return false; // 如果正在加载则不触发加载
            }

            _loadPage(); // 加载更多图片
          }

          return false; // 返回false以允许事件继续冒泡
        },
        child: RepaintBoundary(
          child: Padding(
            padding: EdgeInsets.all(4),
            child: _buildShowBody(),
          ),
        ),
      ),
    );
  }

  Widget _buildShowBody() {
    final theme = Theme.of(context).colorScheme;
    if (_isLoading && _imagePaths.isEmpty) {
      return const Center(child: CircularProgressIndicator());
    } else if (_imagePaths.isEmpty) {
      return Empty();
    } else {
      return CustomScrollView(
        physics: const BouncingScrollPhysics(
          parent: AlwaysScrollableScrollPhysics(),
        ),
        cacheExtent: 300,
        slivers: [
          SliverToBoxAdapter(
            child: SizedBox(height: 0),
          ),
          // 核心改造：SliverPadding 包裹 SliverWaterfallFlow（替代原 SliverGrid）
          SliverGrid.builder(
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: OptionsBase().imageColumns(context) + 1,
              mainAxisSpacing: 4,
              crossAxisSpacing: 4,
              childAspectRatio: 1,
            ),
            itemCount: _assets.length,
            itemBuilder: (context, index) {
              // 图片item
              final currentAsset = _assets[index];
              return GestureDetector(
                onTap: () => _navigateToImageView(index),
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(4),
                  child: FutureBuilder<Uint8List?>(
                    future: _getThumbnail(currentAsset),
                    builder: (_, snapshot) {
                      if (snapshot.hasData) {
                        return Image.memory(snapshot.data!, fit: BoxFit.cover);
                      }
                      // 加载中占位色
                      return BlinkingPlaceholder();
                    },
                  ),
                ),
              );
            },
          ),
          SliverToBoxAdapter(
            child: Padding(
              padding: const EdgeInsets.all(3.0),
              child: SizedBox(
                height: 30,
                child: Center(
                  child: _isLoading
                      ? MyLoading(type: 1, size: 30)
                      : Text(
                          '~ 已经到底了 ~',
                          style: TextStyle(
                            color: theme.onSurface.withAlpha(90),
                          ),
                        ),
                ),
              ),
            ),
          )
        ],
      );
    }
  }
}
